from django import forms
from shunt.models import Verse, Book

class ImportForm(forms.Form):
    file = forms.FileField()
    
    def handle_uploaded_file(self, file):
        out = ""

        for line in file:
            line = line.strip()
            # leave out Insert statements
            if line.startswith("INSERT") == False:
                line = line.rstrip("),").lstrip("(,")
                self.create_verse_object(line)
                out += line
        return out
    
    def create_verse_object(self, line):
        list = []
        string = ""
        #print line
        in_string = False
        already_set = False
        
        # let's build the list
        for c in line:
            #opening a string
            if c == "'" and in_string == False:
                #print 'alert!!! we are in string ' + c
                in_string = True
                already_set = True
            
            if c == "," and in_string == False:
                string = string.strip().rstrip("'\ n").lstrip("'\ n")
                #print "adding string "+string
                list.append(string)
                string = ""
            else:
                string += c
                #print 'appending'
            
            # this would be the closing '
            if c == "'" and in_string == True and already_set == False:
                in_string = False
            
            already_set = False
            
        if len(list) < 8:
            list.append("")
        if len(list) < 9:
            list.append("")
        
        if len(list) == 9:
            # get the associated book from the database
            book = Book.objects.get(book_id=list.pop(2))
            verse = Verse(book_id=book,chapter=list.pop(2),verse=list.pop(2),
                            pilcrow=list.pop(2),verse_scripture=list.pop(2),verse_title=list.pop(2),
                            verse_title_short=list.pop(2))
            
            verse_exist = Verse.objects.filter(book_id=verse.book_id.book_id, chapter=verse.chapter, verse=verse.verse)
            if verse_exist.exists() == False:
                verse.save()
            #verse_exist = Verse.objects.filter(book_id=verse.book_id,chapter=verse.chapter,verse=verse.verse)
            
##            print "verse id: "
##            print verse_exist
##            if verse_exist == None:
##                verse.save()
##                print 'save'
##            else:
##                print 'already saved'
            return verse
        return None